package com.cabd.web.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cabd.service.DownLoadService;
import com.cabd.service.impl.DownLoadServiceImpl;
import com.cabd.staticfinal.DownLoadAndUpLoadPath;
import com.cabd.utils.DownloadUtils;

public class DownLoadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//解决HTTP响应的中文乱码
		response.setContentType("text/html;charset=UTF-8");
		//获得目录和文件名
		String folderName = request.getParameter("folderName");
		String fileName = request.getParameter("fileName");
		//获得客户端信息
		String agent = request.getHeader("User-Agent");
		//处理不同客户端的文件名问题
		String fileNameEncoding = "";
		fileNameEncoding = DownloadUtils.getDownloadFileName(fileName, agent);
		//获得下载文件的文件类型
		response.setContentType(this.getServletContext().getMimeType(fileName));
		//告知浏览器这是一个下载，能解析和不能解析的文件都以附件形式下载
		response.setHeader("Content-Disposition", "attachment;filename="+folderName+fileNameEncoding);
		//完整的文件下载路径
		String path = DownLoadAndUpLoadPath.downLoadAndUpLoadPath+"\\"+folderName+"\\output\\"+fileName;
		ServletOutputStream out = response.getOutputStream();
		DownLoadService downLoadService = new DownLoadServiceImpl();
		//文件由服务器拷贝至客户端
		downLoadService.DownLoadFile(out, path);
//		System.out.println(((User)request.getSession().getAttribute("user")).getId()+"下载了： "+fileName);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}